package com.syqc.monitor.ui.fortify

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.os.IBinder
import android.widget.SeekBar
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.maps.utils.MapUtil
import com.syqc.base.BaseMapActivity
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.databinding.IncludeToolbarBinding
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.toast
import com.syqc.entity.GpsDetail
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityFortifyBinding
import com.syqc.monitor.databinding.IncludeChooseCarBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.net.ServiceHelper
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil


/** @Author Jasper @Time 2021/1/7 @Desc 车辆设防 */
class FortifyActivity : BaseMapActivity<ActivityFortifyBinding>(ActivityFortifyBinding::inflate) {
    //车辆ID
    private var carId = ""

    //半径
    private var radius = 10

    //是否开始设防
    private var isFortify = false

    private var mService: FortifyService? = null

    private val unitRice by lazy { getString(R.string.unit_rice) }
    private lateinit var mSureVB: IncludeSelectSureBinding
    private lateinit var mChooseVB: IncludeChooseCarBinding
    override fun initView() {
        val bind = IncludeToolbarBinding.bind(binding.root)
        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        mChooseVB = IncludeChooseCarBinding.bind(binding.root)
        immersionBar { titleBar(bind.mToolbar) }
        ToolbarHelper.setToolbar(this, R.string.title_other_fortify)

        binding.fortifyRadius.text = "$radius $unitRice"
        mSureVB.tvSure.setText(R.string.desc_fortify_open)
        LiveDataBus.get().with("fortify_location", GpsDetail::class.java)
            .observe(this) { setMapMarker(it) }
    }

    override fun initMap() {
        MapUtil.initMapSetting(mAMap)
        initIntent()
    }

    override fun setListener() {
        mChooseVB.lrvChooseCar.filterFast {
            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this)
            } else {
                launcher.launchAct<ChooseCarActivity>(this)
            }
            stopFortify()
        }

        mSureVB.tvSure.filterFast {
            if (isFortify) {
                stopFortify()
                R.string.toast_close_fortify.toast(this)
            } else {
                startFortify()
            }
        }

        binding.seekbarRadius.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                radius = progress + 10
                binding.fortifyRadius.text = "$radius $unitRice"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })
        hasLive.observe(this) {
            if (it) {
                isFortify = true
                mSureVB.tvSure.setText(R.string.desc_fortify_close)

                R.string.toast_open_fortify.toast(this)
                if (mService == null) {
                    bindService(
                        Intent(this, FortifyService::class.java)
                            .putExtra(Keys.INTENT_CAR_ID, carId)
                            .putExtra(Keys.INTENT_OTHER, radius),
                        serviceConn,
                        BIND_AUTO_CREATE
                    )

                } else {
                    mService?.startRequest(carId, radius)
                }
                binding.seekbarRadius.isEnabled = false
            }
        }
        //放大
        binding.ivMapZoomIn.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomOut(), 600, null)
        }

        //缩小
        binding.ivMapZoomOut.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomIn(), 600, null)
        }
    }

    /** 停止设防 */
    private fun startFortify() {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        getGpsInfo()
    }

    /**
     */
    private fun stopFortify() {
        centerLatLng = null
        isFortify = false
        mSureVB.tvSure.setText(R.string.desc_fortify_open)
        binding.seekbarRadius.isEnabled = true
        mService?.stopRequest()
        mAMap.clear()
        carMarker = null
    }

    //定位时位置
    private var centerLatLng: LatLng? = null

    //车辆图标
    private var carMarker: Marker? = null

    /** 根据定位信息设置 */
    private fun setMapMarker(entity: GpsDetail) {
        val latLng = LatLng(entity.glat.toDouble(), entity.glng.toDouble())
        if (centerLatLng == null) {
            centerLatLng = latLng
            mAMap.clear()
            val span: Int = when {
                radius > 200 -> {
                    16
                }

                radius > 130 -> {
                    17
                }

                radius > 60 -> {
                    18
                }

                else -> {
                    19
                }
            }
            mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(centerLatLng, span.toFloat()))
            mAMap.addMarker(
                MarkerOptions().anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location_center))
                    .position(latLng)
            )
            if (carMarker == null) {
                carMarker = MapUtil.addAndGetMarker(
                    mAMap, latLng,
                    BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker_move)
                )
                carMarker!!.rotateAngle = entity.drct.toFloat()
            }
            mAMap.addCircle(
                CircleOptions().center(latLng).radius(radius.toDouble()).strokeColor(Color.BLUE)
                    .fillColor(Color.argb(50, 1, 1, 1))
                    .strokeWidth(2f)
            )
        } else {
            if (carMarker == null) {
                carMarker = MapUtil.addAndGetMarker(
                    mAMap, latLng,
                    BitmapDescriptorFactory.fromResource(R.mipmap.ic_marker_move)
                )
                carMarker!!.rotateAngle = entity.drct.toFloat()
            } else {
                carMarker!!.position = latLng
                carMarker!!.rotateAngle = entity.drct.toFloat()
            }
            val builder = LatLngBounds.Builder()
            builder.include(centerLatLng)
            builder.include(latLng)
            MapUtil.showMapBounds(mAMap, builder.build())
        }
    }

    private val launcher = registerResultOk { result -> result.data?.handleCarInfo(true) }

    //处理调转过来的数据
    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        if (carId == null) {
            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this)
            } else {
                launcher.launchAct<ChooseCarActivity>(this)
            }
            return
        }
        intent.handleCarInfo()
        binding.lrvChooseCar.isEnabled = false
    }

    private fun Intent.handleCarInfo(isIntent: Boolean = false) {
        val carId = getStringExtra(Keys.INTENT_CAR_ID) ?: ""
        val carName = if (isIntent) {
            getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
        } else {
            getStringExtra(Keys.INTENT_PLATE) ?: ""
        }
        mChooseVB.lrvChooseCar.setRightText(carName)
        centerLatLng = null
        carMarker?.remove()
        carMarker = null
        mAMap.clear()
        this@FortifyActivity.carId = carId

    }

    //绑定方式启动服务
    private val serviceConn by lazy {
        object : ServiceConnection {
            /**
             * 与服务器端交互的接口方法 绑定服务的时候被回调，在这个方法获取绑定Service传递过来的IBinder对象，
             * 通过这个IBinder对象，实现宿主和Service的交互。
             */
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                // 获取Binder
                val binder: FortifyService.FortifyBinder = service as FortifyService.FortifyBinder
                mService = binder.service
                mService?.startRequest(carId, radius)
            }

            /**
             * 当取消绑定的时候被回调。但正常情况下是不被调用的，它的调用时机是当Service服务被意外销毁时，
             * 例如内存的资源不足时这个方法才被自动调用。
             */
            override fun onServiceDisconnected(name: ComponentName?) {
                mService = null
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        stopFortify()
        mService?.let {
            unbindService(serviceConn)
        }
        mService = null
    }

    private var hasLive = MutableLiveData<Boolean>()

    private fun getGpsInfo() {
        ServiceHelper.getRepository().getGpsRInfo("", carId, true, true)
            .autoDispose(scopeProvider)
            .subscribe({
                if (it.isNullOrEmpty()) {
                    toast(R.string.toast_no_location_msg)
                    hasLive.postValue(false)
                    return@subscribe
                }
                hasLive.postValue(true)
            }, {
                hasLive.postValue(false)
                it.message?.toast(this)
            })
    }


}